//
//  ContactEditViewController.m
//  Guazi
//
//  Created by koolearn on 11-5-12.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ContactGroupViewController.h"
#import "FriendGroup.h"
#import "UserService.h"
#import "FriendsViewController.h"
#import "GuaziAppDelegate.h"


@interface ContactGroupViewController(private)
- (NSInteger) getIndexAtGroups:(sqlite_int64)groupId;
@end



@implementation ContactGroupViewController

@synthesize user;

#pragma mark -
#pragma mark Initialization


- (id) initWithStyle:(UITableViewStyle)style user:(User*)aUser
{
    self = [super initWithStyle:style];
	if ( self ) {
		self.user = aUser;
		selectedGroups = nil;
	}
	return self;
}



#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	
	UIBarButtonItem* saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave 
																				target:self action:@selector(save)];
	self.navigationItem.rightBarButtonItem = saveButton;
	[saveButton release];
	
	allGroups = [[FriendGroup loadGroups:false onlyRealGroup:YES] retain];
	userGroups = [[FriendGroup getGroupsWithUserId:user.userId] retain];
	
	selectedGroups = [[NSMutableDictionary alloc] initWithCapacity:[userGroups count]];
	for ( FriendGroup* g in userGroups ) {
		NSString* key = [NSString stringWithFormat:@"%lld", g.groupId];
		[selectedGroups setObject:@"" forKey:key];
	}

    userView = [[UserView alloc] initWithFrame:CGRectMake(0, 0, 320, 387)];
    [userView setUser:user];
}


- (void) save
{
    NSMutableArray* oldGroups = [NSMutableArray arrayWithCapacity:[userGroups count]];
    for ( FriendGroup* group in userGroups ) {
        if ( group.groupId > 0 ) {
            [oldGroups addObject:[NSString stringWithFormat:@"%lld", group.groupId]];
        }
    }
    
    NSArray* newGroups = [selectedGroups allKeys];
    
    [UserService setUserGroups:user.userId groups:newGroups];
    FriendsViewController* controller = [[GuaziAppDelegate getAppDelegate] friendsViewController];
    [controller refreshSetUserGroup:user oldGroups:oldGroups newGroups:newGroups];
    
    [self.navigationController popViewControllerAnimated:YES];
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [allGroups count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"FriendGroupCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    FriendGroup* group = [allGroups objectAtIndex:indexPath.row];
    cell.textLabel.text = group.name;
    NSString* key = [NSString stringWithFormat:@"%lld", group.groupId];
    if ( [selectedGroups objectForKey:key] != nil ) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
	
    return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	if ( section == 0 ) {
		return userView;
	}
	else {
		return nil;
	}
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	if ( section == 0 ) {
        return 80;
	}
	else {
		return 0;
	}
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];

	UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
	if ( cell.accessoryType == UITableViewCellAccessoryCheckmark ) {
		cell.accessoryType = UITableViewCellAccessoryNone;
        FriendGroup* group = [allGroups objectAtIndex:indexPath.row];
        [selectedGroups removeObjectForKey:[NSString stringWithFormat:@"%lld", group.groupId]];
	}
	else {
		cell.accessoryType = UITableViewCellAccessoryCheckmark;
        FriendGroup* group = [allGroups objectAtIndex:indexPath.row];
        [selectedGroups setObject:group forKey:[NSString stringWithFormat:@"%lld", group.groupId]];
	}
}


- (NSInteger) getIndexAtGroups:(sqlite_int64)groupId
{
	FriendGroup* g = nil;
	for ( NSInteger i=0; i<[allGroups count]; i++ ) {
		g = [allGroups objectAtIndex:i];
		if ( g.groupId == groupId ) {
			return i;
		}
	}
	
	return -1;
}



#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	[allGroups release];
	[userGroups release];
	[selectedGroups release];
	self.user = nil;
}


- (void)dealloc {
	[user release];
	[allGroups release];
	[userGroups release];
	[selectedGroups release];
    [super dealloc];
}


@end

